<template>
  <view>
    <up-swiper
        :list="detailData.photos"
        height="400"
    ></up-swiper>

    <view class="desc-card">
      <view class="flex-block m-15" style="justify-content: space-between;">
        <view style="flex: 1; width: 0;" class="p-r-10">
          <view class="txt-large txt-ellipsis">{{ activeSpeciaData.name }}</view>
          <view class="u-tips-color u-m-t-10" style="white-space: pre-line; line-height: 1.8;">
            {{ activeSpeciaData.subTitle }}
          </view>
        </view>
        <view>
          <up-icon name="bookmark-fill" :size="28" class="u-warning-dark"></up-icon>
        </view>
      </view>
      <view class="m-15 u-m-b-0">
        <text class="txt-large">￥{{ activeSpeciaData.price }}</text>
        <text class="txt-large">/{{ activeSpeciaData.unit }}</text>
        <text class="txt-small txt-deco u-tips-color u-m-l-10">￥{{ activeSpeciaData.guidePrice }}</text>
      </view>
    </view>

    <view class="u-p-l-30 u-p-r-30 u-p-t-20 u-p-b-10 u-m-t-30">
      <y-radio title="" :data="speciaData" v-model:index="currentIndex" showType="card" />
    </view>

    <template v-if="detailData.instructionRichText">
      <view class="txt-small m-15">
        <up-divider text="描述"></up-divider>
        <rich-text :nodes="descRich" class="rich-img"></rich-text>
      </view>
    </template>

    <template v-if="detailData.detailRichText">
      <up-divider text="商品详情"></up-divider>
      <view>
        <rich-text :nodes="detailRich" class="rich-img"></rich-text>
      </view>
    </template>

    <template v-if="detailData.saleRichText">
      <view class="txt-small m-15">
        <up-divider text="售后"></up-divider>
        <rich-text :nodes="saleRich" class="rich-img"></rich-text>
      </view>
    </template>

    <view style="height: 80px;"></view>

    <view class="flex-block p-10" style="position: fixed; bottom: 0; left: 0; z-index: 999; background-color: #ffffff; width: 100%; box-sizing: border-box;">
      <view style="flex: 0.3; margin-right: 10px;">
        <up-button :color="$u.color.success" openType="share">分享</up-button>
      </view>
      <view style="flex: 1">
        <up-button :color="$u.color.mainColor" @click="showPop">我想要</up-button>
      </view>
    </view>

    <u-popup ref="popup" mode="bottom" :customStyle="{'max-height': 500 + 'px'}" :show="visible" :closeOnClickOverlay="true">
      <view class="close-icon">
        <u-icon name="close" @click="closePop"></u-icon>
      </view>
      <view class="u-p-20">
        <view class="flex-block" style="justify-content: space-between; align-items: flex-end;">
          <image :src="activeSpeciaData.avatar" style="width: 128rpx; height: 128rpx;" mode="aspectFill" />
          <view style="flex: 1; width: 0;" class="p-r-10 u-p-l-20">
            <view class="txt-large txt-ellipsis">{{ activeSpeciaData.name }}</view>
            <view class="u-m-t-10">
              <text class="txt-large u-m-r-10">¥{{ activeSpeciaData.price }}/{{ activeSpeciaData.unit }}</text>
            </view>
          </view>
          <view>
            <uni-number-box
              v-model="activeSpeciaData.numberValue"
              :min="1"
            ></uni-number-box>
          </view>
        </view>

        <view class="p-t-10">
          <y-radio title="规格" :data="speciaData" v-model:index="currentIndex" />
        </view>

        <view style="height: 80px;"></view>
        <view class="flex-block p-10" style="position: fixed; bottom: 0; left: 0; z-index: 999; background-color: #ffffff; width: 100%; box-sizing: border-box;">
          <view style="flex: 1" class="p-r-10">
            <up-button type="info" @click="addCart('2')">加入购物车</up-button>
          </view>
          <view style="flex: 1">
            <up-button :color="$u.color.mainColor" @click="toOrder">创建订单</up-button>
          </view>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
import htmlParser from '@/utils/html-parser'
import cache from '@/utils/cached.js'
export default {
  data() {
    return {
      goodsId: '',
      detailData: {},
      speciaValue: 1,
      visible: false,
      currentIndex: 0
    }
  },
  computed: {
    speciaData() {
      if (!this.detailData.skus) return []
      return this.detailData.skus.length ? this.detailData.skus : [{
        ...this.detailData,
        // 商品没得sku数据，为了视觉效果，把detail的基础信息填充进skus，作为sku临时展示，但不能设置id
        id: null
      }]
    },
    activeSpeciaData() {
      if (!this.speciaData.length) return {}
      return {
        ...this.speciaData[this.currentIndex],
        numberValue: 1,
        subTitle: this.detailData.subTitle,
        name: this.detailData.name,
        unit: this.detailData.unit
      }
    },
    descRich() {
      if (this.detailData.instructionRichText) {
        const nodes = htmlParser(this.detailData.instructionRichText)
        if (!nodes[0].children) {
          nodes.forEach(item => {
            item['attrs'] = {
              style: 'line-height: 2;'
            }
          })
          return nodes
        }
        let imgNodes = nodes[0].children.filter(v => v.name == 'img')
        imgNodes.forEach(item => {
          item.attrs.src = item.attrs.src.replace('http://', 'https://')
          item.attrs.style = 'width: 100%; height: auto;'
        })
        return nodes
      } else {
        return []
      }
    },
    saleRich() {
      if (this.detailData.saleRichText) {
        const nodes = htmlParser(this.detailData.saleRichText)
        if (!nodes[0].children) return nodes
        let imgNodes = nodes[0].children.filter(v => v.name == 'img')
        imgNodes.forEach(item => {
          item.attrs.src = item.attrs.src.replace('http://', 'https://')
          item.attrs.style = 'width: 100%; height: auto;'
        })
        return nodes
      } else {
        return []
      }
    },
    detailRich() {
      if (this.detailData.detailRichText) {
        const nodes = htmlParser(this.detailData.detailRichText)
        
        if (!nodes[0].children) return nodes
        nodes.forEach(item => {
          let imgNodes = item.children.filter(v => v.name == 'img')
          imgNodes.forEach(row => {
            row.attrs.src = row.attrs.src.replace('http://', 'https://')
            row.attrs.style = 'width: 100%; height: auto;'
          })

          if (item.name == 'p' && item.children.findIndex(v => v.name == 'img') == -1) {
            if (item.attrs) item.attrs.style = 'margin: 10px;'
          }
          if (item.name == 'h2' || item.name == 'h1') {
            if (item.attrs) item.attrs.style = 'margin: 10px;'
          }
        })
        
        return nodes
      } else {
        return []
      }
    },
  },
  async onLoad(options) {
    console.log('goodsInfo load')
    this.goodsId = options.id || ''
    await this.getDetail()

    //#ifdef MP-WEIXIN
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    });
    //#endif
  },
  methods: {
    async getDetail() {
      const data = await this.$api.goods.detail({id: this.goodsId})
      this.detailData = data.data || {}
    },
    showPop() {
      this.visible = true
    },
    closePop() {
      this.visible = false
    },
    // 订单金额起送额获取
    async checkPrice() {
      const res = await this.$api.config.dict({
        code: 'PayThreshold'
      })
      const payThreshold = res.data.details[0].displayText
      const val = this.activeSpeciaData.numberValue * this.activeSpeciaData.price
      if (payThreshold > val) {
        const { confirm, cancel } = await uni.showModal({
          title: '温馨提示',
          content: `单笔订单金额未满${payThreshold}元,可先加入购物车,再一起下单.`,
          confirmText: '加购物车',
          cancelText: '再逛逛'
        })

        if(confirm) {
          this.addCart('1')
        } else {
          uni.navigateBack({})
        }
        return false
      } else {
        return true
      }
    },
    async toOrder() {
      const status = await this.checkPrice()
      if (!status) return;

      let { code } = await this.$api.cart.add({
        "goodsId": this.detailData.id,
        "skuId": this.activeSpeciaData.id,
        "quantity": this.activeSpeciaData.numberValue
      })

      if (code != 200) {
        uni.showToast({
          title: '创建订单失败',
          mask: true
        })
      }

      this.closePop()
      uni.navigateTo({ url: '/pages/create-order/create-order' })
    },
    async addCart(str) {
      let {code} = await this.$api.cart.add({
        "goodsId": this.detailData.id,
        "skuId": this.activeSpeciaData.id,
        "quantity": this.activeSpeciaData.numberValue
      })

      if (code == 200) {
        this.closePop()
        if (str == '1') {
          uni.showToast({
            title: '添加购物车成功',
            mask: true
          })
        } else if (str == '2') {
          uni.showModal({
            title: '提示',
            content: '是否去购物车结算',
            showCancel: true,
            success: ({ confirm, cancel }) => {
              if (confirm) {
                uni.reLaunch({ url: '/pages/index/index?index=1' })
              }
            }
          })
        }
      } else {
        uni.showToast({
          title: '添加购物车失败',
          mask: true
        })
      }
    }
  },
  onShareAppMessage() {
    const userInfo = cache.getUserInfo()
    let params = `id=${encodeURIComponent(this.goodsId)}&userId=${encodeURIComponent(userInfo.userId)}&from=goodsInfo`
    console.log('params', params)
    return {
      title: this.detailData.name + '|' + this.detailData.subTitle,
      path: `/pages/index/index?${params}`,
      imageUrl: this.detailData.avatar,
      fail(err) {
        console.log(err)
      },
      complete() {
        console.log('complete')
      }
    }
  },
  onShareTimeline() {
    const userInfo = cache.getUserInfo()
    let params = `id=${encodeURIComponent(this.goodsId)}&userId=${encodeURIComponent(userInfo.userId)}&from=goodsInfo`
    console.log('params', params)
    return {
      title: this.detailData.name + '|' + this.detailData.subTitle,
      path: `/pages/index/index?${params}`,
      imageUrl: this.detailData.avatar,
      fail(err) {
        console.log(err)
      },
      complete() {
        console.log('complete')
      }
    }
  }
}
</script>

<style lang="stylus" scoped>
.desc-card
  background: #fff
  width 90%
  min-height: 130px
  box-shadow: 0px 8px 10px rgba(0,0,0,0.085)
  margin 0 auto
  border-radius 15px
  position relative
  margin-top -40px
  padding 0.1px
  padding-bottom: 15px;

.close-icon
  background: #fff;
  position absolute;
  top: -80rpx;
  right: 0px;
  width: 80rpx;
  height: 80rpx;
  display: flex;
  justify-content: center;
  align-items: center;

:deep(.rich-img img)
  width 100%
  height auto
</style>